using UnityEngine;
using System.Collections;

public class EnemyCheckState : State<EnemyControl> 
{
	#region Singleton

    private static EnemyCheckState instance = new EnemyCheckState();
    public static EnemyCheckState Instance { get { return instance; } }
    private EnemyCheckState() { }

    #endregion

    #region State

    public override void OnEnter(EnemyControl behaviour)
    {
        behaviour.coneVision.renderer.material.SetColor(TextConstants.TINT_COLOR, behaviour.warnConeColor);
        behaviour.MoveTo(behaviour.playerLastLocation, behaviour.checkSpeed);
    }

    public override void OnUpdate(EnemyControl behaviour)
    {
        if (behaviour.IsPlayerInViewRange())
            behaviour.State = EnemyAlertState.Instance;
        else if (behaviour.IsOverPoint(behaviour.playerLastLocation, behaviour.playerOffset)) /* Arrive the point */ 
        {
            if (behaviour.IsPlayerInRayRange()) /* Look in player direction */
                behaviour.State = EnemyAlertState.Instance;
            else if (behaviour.probSearch <= Random.value) /* Check random */
                behaviour.State = EnemyPatrolState.Instance;
            else
                behaviour.State = EnemySearchState.Instance;
        }       
    }

    public override void OnExit(EnemyControl behaviour)
    {
        behaviour.Controller.ResetPath();
    }

    public override void OnAction(string name, EnemyControl behaviour, object value)
    {
        switch (name)
        {
            case ActionConstants.TRIGGER:
                this.OnTrigger(behaviour, value as Collider);
                break;
        }
    }

    #endregion

    #region Methods

    private void OnTrigger(EnemyControl behaviour, Collider other)
    {
        if (other.tag == TagConstants.TAG_SOUND_AREA)
        {
            float prevProb = behaviour.probSearch;
            behaviour.SoundHeard(other.transform.position);
            behaviour.probSearch = Mathf.Max(behaviour.probSearch, prevProb);
            behaviour.MoveTo(behaviour.playerLastLocation, behaviour.checkSpeed);
        }
    }

    #endregion
}
